package validate

import (
	"context"
	"gitee.com/bobo-rs/idea-space-framework/framework/service"
	"gitee.com/bobo-rs/idea-space-framework/pkg/utils"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/util/gvalid"
)

type (
	// RuleAttachIdExistsItem 附件ID检测属性
	RuleAttachIdExistsItem struct {
		AttachId string `json:"attach_id"`
	}
)

// RuleRegisterAttachment 注册附件规则
func RuleRegisterAttachment() {
	gvalid.RegisterRuleByMap(map[string]gvalid.RuleFunc{
		`attach-id-exists`: RuleAttachIdExists,
	})
}

// RuleAttachIdExists 通过附件ID检测附件是否存在
func RuleAttachIdExists(ctx context.Context, in gvalid.RuleFuncInput) error {
	var (
		item = RuleAttachIdExistsItem{}
	)
	if err := in.Data.Scan(&item); err != nil {
		return gerror.Wrap(err, `扫描附件ID到RuleAttachIdExistsItem失败`)
	}
	// 附件ID是否存在
	if len(item.AttachId) != 32 || !utils.AlphaNum(item.AttachId) {
		return gerror.New(`附件ID格式错误`)
	}
	// 附件是否存在
	if ok := service.Attachment().CheckAttachmentExistsByAttachId(ctx, item.AttachId); !ok {
		return gerror.New(`附件不存在`)
	}
	return nil
}
